<?php
namespace Wanecho\Mobilelogin\Api\Controllers;

use Psr\Http\Message\ResponseInterface as Response;
use Flarum\Settings\SettingsRepositoryInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Laminas\Diactoros\Response\JsonResponse;
use Flarum\User\User;
use Illuminate\Support\Arr;
use Flarum\User\UserRepository;
use Wanecho\Mobilelogin\Api\WanechoSms;
use Flarum\Http\RequestUtil;

class SmsCheckController implements RequestHandlerInterface
{

    /**
     * @var SettingsRepositoryInterface
     */
    protected $users;
    
    protected $valid_period = 30 * 3; // sms timeout 3 minute

    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }

    public function handle(ServerRequestInterface $request): Response
    {
        
        $body = $request->getParsedBody();
        $phone = Arr::get($body, 'phone');
        $code = (int) Arr::get($body, 'code');
        
        if ($phone == '') {
            return new JsonResponse('请输入手机号码', 500);
        }
        if ($code == '') {
            return new JsonResponse('请输入短信验证码', 500);
        }

        $actor = RequestUtil::getActor($request);
        $sms_response = WanechoSms::where([
            'mobile' => $phone,
            'user_id' => $actor->id,
            // 'code' => $code,
            'is_active' => 0
        ])->orderBy('id', 'desc')->first();

        if (!$sms_response) {
            return new JsonResponse('请先发送验证码', 500);
        }
        if ((int) $sms_response->code !== $code) {
            return new JsonResponse('验证码错误', 500);
        }
        $sms_response->is_active = 1;
        $sms_response->save();
        if ($sms_response->created_at > date('Y-m-d H:i:s', time() + $this->valid_period)) {
            return new JsonResponse('验证码已过期，请重新获取', 500);
        }
        //检测手机号是否绑定
        $user = User::where(['mobile' => $phone])->first();
        if($user){
            return new JsonResponse('该手机号已绑定', 500);
        }
        //绑定手机号
        $user = User::where(['id' => $actor->id])->first();
        $user->mobile = $phone;
        if($user->save()){
            return new JsonResponse('绑定成功', 200);
        }else{
            return new JsonResponse('绑定失败', 500);
        }

    }

}